from Crypto.PublicKey import ECC
from Crypto.Hash import SHA256
from Crypto.Signature import DSS
import Crypto.Cipher.PKCS1_OAEP as oaep
from Crypto import Random

# 签名
def ECC_sign(message,key):
    signer = DSS.new(key, 'fips-186-3')
    hasher = SHA256.new(message.encode())  # Hash对象，取内容摘要
    # hasher.update(msg.encode()) # 换种方式使用也可以
    sign_obj = signer.sign(hasher)  # 用私钥对消息签名
    print('签名内容：', sign_obj)

    with open('../data/test/sign.bin', 'wb') as f:
        f.write(sign_obj)

# 验证签名
def ECC_verify(message,key):
    with open('../data/test/sign.bin', 'rb') as f:
        sign_new = bytearray(f.read())  # 签名内容(二进制)，并转成bytearray，以便修改
    #sign_new.append(0x32)  # 模拟错误的签名
    print('收到签名：', sign_new)

    verifer = DSS.new(key.public_key(), 'fips-186-3')  # 使用公钥创建校验对象
    hasher = SHA256.new(message.encode())  # 对收到的消息文本提取摘要

    try:
        verifer.verify(hasher, sign_new)  # 校验摘要（本来的样子）和收到并解密的签名是否一致
        print("The signature is valid.")
    except (ValueError, TypeError):
        print("The signature is not valid.")

def ECC_encrypt(plain_text,key):
    cipher_obj = oaep.new(key.public_key())
    cipher_text = cipher_obj.encrypt(plain_text.encode())
    return cipher_text

def ECC_decrypt(cipher_text,key):
    cipher_obj = oaep.new(key)
    plain_byte = cipher_obj.decrypt(cipher_text,Random.new().read)
    plain_text = plain_byte.decode()

    return plain_text


# 生成ECC密钥对
key = ECC.generate(curve='P-256')
message = 'I am MKing Hello Everyone'
ECC_sign(message,key)
ECC_verify(message,key)

#cipher = ECC_encrypt(message,key)
#ECC_decrypt(cipher,key)